package org.example.tcp.server;

import org.example.common.MyConverter;
import org.example.tcp.TcpData;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Set;

public class MyRunable implements Runnable{
    private Socket socket = null;
    private  HashMap<String,Socket> map = TcpServer.map;
    public MyRunable(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        while(true){
            try{
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int len = inputStream.read(bytes);
                TcpData tcpData = MyConverter.fromByteArray(bytes);
                String name = tcpData.getSource();
                if (tcpData.getDestination().equals("down")) {
                    map.remove(socket.getInetAddress()+"/"+socket.getPort());
                    System.out.println(socket.getInetAddress()+"/"+socket.getPort()+"断开连接！！");
                    break;
                }
                if (tcpData.getDestination().equals("all")){
                    Set<String> keyset = map.keySet();
                    for (String key : keyset) {
                        if (name.equals(key)) continue;
                        Socket socket = map.get(key);
                        OutputStream outputStream = socket.getOutputStream();
                        outputStream.write(tcpData.getMessage().getBytes());
                    }
                }else {
                    String destination = tcpData.getDestination();
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        if (!destination.equals(key)) continue;
                        Socket socket = map.get(key);
                        OutputStream outputStream = socket.getOutputStream();
                        outputStream.write(tcpData.getMessage().getBytes());
                        break;
                    }
                }
            }catch (Exception e){
                map.remove(socket.getInetAddress()+"/"+socket.getPort());
                System.out.println(socket.getInetAddress()+"/"+socket.getPort()+"断开连接！！");
               break;
            }
        }


    }
}
